clear all 
set more off

global mydir "C:\XYZ" // set working directory

global data "$mydir\data"
cd "$mydir\data\buffer"
set matsize 11000
set maxvar 32700

import delimited intersection_buffer_facility_5mile.csv, clear
gen year=2010
rename geoid10 bgeoid
rename aland10 aland
rename awater10 awater
rename intptlat10 blat
rename intptlon10 blon
rename countyfp10 cntyid
keep code deslat deslon j year cntyid bgeoid aland awater blat blon
sort bgeoid

keep if aland>0
*Calculate Vdistance for pairs facility-blocks
geodist blat blon deslat deslon, miles gen(Vdis)
sum Vdis
sort year code Vdis
by year code: gen ycdup=cond(_N==1,0,_n)
sum Vdis if ycdup<=1 // smallest distances of pairs

drop ycdup
preserve
keep if Vdis <=1
save demographics_buffer_1mile, replace
restore
preserve
keep if Vdis <=2
save demographics_buffer_2mile, replace
restore
preserve
keep if Vdis <=3
save demographics_buffer_3mile, replace
restore
preserve
keep if Vdis <=4
save demographics_buffer_4mile, replace
restore
preserve
keep if Vdis <=5
save demographics_buffer_5mile, replace
restore

forval i=1/5 {
*** Merge with block demo info
use demographics_buffer_`i'mile, clear
sort year bgeoid
merge m:1 year bgeoid using $data\demographics\block_demographics_2010_CA
keep if _merge==3 //_merge==1 must have 0, or aland==0 blocks
drop _merge
sort year code
local varl "pop white black asian hispanic house ochouse hh"
foreach v in `varl' {
	by year code: egen B`v'=total(`v')
}
*assign Bincome (community income) by block income weighted by block pop (block income = block group income)
gen popinc=mdhhinc*pop
by year code: egen Bmdhhinc_del=total(popinc)
gen Bmdhhinc=Bmdhhinc_del/Bpop
drop popinc *_del

bys year code: gen ycdup=cond(_N==1,0,_n)
keep if ycdup<=1
keep year code B*
gen B0pop= Bpop==0
label var Bpop "population at block"
label var Bwhite "white population at block"
label var Bblack "black population at block"
label var Basian "Asian population at block"
label var Bhispanic "Hispanic population at block"
label var Bhouse "# houses at block"
label var Bhh "# household at block"
label var Bmdhhinc "median household income at block group"
save demographics_buffer_`i'mile, replace
}
